//
//  Init.m
//  ActiveDeck
//
//  Created by Chiao-Wei Liu on 2011/2/7.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "Init.h"
#import "HttpRequest.h"
#import "GDataXMLNode.h"
#import "AD_Button.h"
#import "AD_TextBox.h"
#import "AD_Page.h"
#import "AD_Slide.h"
#import	"AD_Category.h"
#import "AD_Word.h"
#import "AD_Image.h"
#import "AD_Resource.h"
#import "AD_Words.h"
#import "AD_Video.h"
#import "AD_ViewPort.h"
#import "AD_Kiosk.h"
#import "AD_Layer.h"
#import "AD_Grade.h"
#import "AD_Question.h"
#import "AD_ParallaxView.h"
#import "AD_WebView.h"


#define MaxViewTag 1000

@implementation Init
@synthesize Resume, xmlError , iVersion, xmlnsLink, Conf_Kiosk;
@synthesize mu_Arr_Resources, mu_Arr_Slides, progress, cancel,PID,m_ResourcePath,m_ConfigPath, canExportToPDF,webServiceEndPoint, pagesVisited, hasSecondarySubscription, channelFormat, shouldDownload, configXMLString, xmlFilePath, PresentDir, Authentication;

-(id)delegate
{
	return _delegate;
}

-(void)setDelegate:(id)delegate
{
	_delegate = delegate;
}

#pragma mark -
#pragma mark Initialize Presentation

- (void)retrievePresentationResources
{
    NSData *xmlData;
    xmlData = [configXMLString dataUsingEncoding:NSUTF8StringEncoding];
    [xmlData writeToFile:xmlFilePath atomically:YES];
    
    //[_delegate hideAll:TRUE];
    
    [self LoadXML:xmlData PresentDir:PresentDir];
    
    [self DownloadResource:PID
               resourceDir:PresentDir
               xmlFilePath:xmlFilePath
          autheticationXML:Authentication];
    
    pagesVisited = [[NSMutableArray alloc] init];
}

-(BOOL)InitialConfig:(int)PresentID
	  Authentication:(NSString *)AuthenticationXML
         HasInternet:(BOOL)HasInternet
{
    
    Authentication = AuthenticationXML;
    
    m_ResourcePath = [NSString stringWithFormat:@"%@/Config.svc/GetResource", [HttpRequest GetSvcURL]]; 
    m_ConfigPath = [NSString stringWithFormat:@"%@/Config.svc/GetPresentation", [HttpRequest GetSvcURL]];
    
    PID = PresentID;
    cancel = FALSE;
    
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *docDir = [paths objectAtIndex:0];
	PresentDir = [[NSString alloc] initWithFormat:@"%@/%d", docDir, PresentID];
	xmlFilePath = [[NSString alloc] initWithFormat:@"%@/%d%@", PresentDir,PresentID, @".xml"];
    
    
	NSFileManager *nsFM = [NSFileManager defaultManager];
	BOOL isDir = YES;
    
	if(![nsFM fileExistsAtPath:PresentDir isDirectory:&isDir]){
		[nsFM createDirectoryAtPath:PresentDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    if(HasInternet){
        shouldDownload = YES;
        HttpRequest *configRequest = [HttpRequest alloc];
        while (!cancel) {
            
            configXMLString = [configRequest XML_PostRequest:AuthenticationXML urlString:[NSString stringWithFormat:@"%@/%d", m_ConfigPath , PresentID]];
            
            if([configXMLString isEqualToString:@"NOCONTENT"])
            {
                UIAlertView *alertMSG = [UIAlertView alloc];
                alertMSG = [alertMSG initWithTitle:@"Error Message"
                                           message:@"Presentation has not been published yet."
                                          delegate:self 
                                 cancelButtonTitle:@"OK" 
                                 otherButtonTitles:nil];
                
                [alertMSG show];
                [alertMSG release];
                
                [self performSelectorOnMainThread:@selector(UpdateWaitingLabel:) withObject:@"FALSE" waitUntilDone:NO];            
                break;   
            }
            
            NSString *searchFor = @"Error";
            NSRange range = [configXMLString rangeOfString:searchFor];
            
            if (range.location == NSNotFound)
            {
                searchFor = @"BLOCKED";
                range = [configXMLString rangeOfString:searchFor];
                
                if(range.location != NSNotFound){
                    [self performSelectorOnMainThread:@selector(UpdateWaitingWithBlocked) withObject:nil waitUntilDone:NO];
                    break;
                }
                
                [self performSelectorOnMainThread:@selector(UpdateWaitingLabel:) withObject:@"FALSE" waitUntilDone:NO];            
                break;           
            }
            else
            {
                [self performSelectorOnMainThread:@selector(UpdateWaitingLabel:) withObject:@"TRUE" waitUntilDone:NO];  
                [NSThread sleepForTimeInterval:10];
            }
            
        }
        
        [configRequest release];

        
    } else {
        configXMLString = [[NSString alloc] initWithContentsOfFile:xmlFilePath encoding:NSUTF8StringEncoding error:nil];
    
    }    
    
    if(!HasInternet && configXMLString)
    {  
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"Internet Connection Failure"
								   message:@"We can't get the latest version of this presentation.  Do you want to load the current version?"
								  delegate:self 
						 cancelButtonTitle:@"Cancel" 
						 otherButtonTitles:@"OK",nil];
		
		[alertMSG show];
        [alertMSG release];
        
        		
    } else if(!HasInternet && !configXMLString) {
        UIAlertView *alertMSG = [UIAlertView alloc];
        alertMSG = [alertMSG initWithTitle:@"No Previous Download"
                                   message:@"No Internet connection is available and this presentation has not been downloaded previously."
                                  delegate:self 
                         cancelButtonTitle:@"OK" 
                         otherButtonTitles:nil];
        
        [alertMSG show];
        [alertMSG release];
        
        return NO;

        
    }
    
    if(shouldDownload){
        [self retrievePresentationResources];
        
        return YES;
    }
    
    return NO;
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  {
    if(buttonIndex == 1)
    {
        [self retrievePresentationResources];
    }
}

#pragma mark -
#pragma mark Download all the Resources 

-(void)DownloadResource:(int)PresentID
			resourceDir:(NSString *)PresentFolder
            xmlFilePath:(NSString *)xmlPath
	   autheticationXML:(NSString *)authenticationXML
{
    NSFileManager *nsFM = [NSFileManager defaultManager];
	BOOL isDir = NO;
    
	BOOL imageCorrupted = FALSE;
	BOOL download = TRUE;
    
	float i=1;
	
    
	
	NSLog(@"Doc Directory: %@", PresentFolder);
	
	download = [self CheckVersion];
    
	for(AD_Resource *ResourceOB in  mu_Arr_Resources)
	{
        NSAutoreleasePool *resourcePool = [[NSAutoreleasePool alloc] init];
        
        HttpRequest *imageRequest = [[HttpRequest alloc]autorelease];
        imageRequest.showAlert = TRUE;
        
        if(cancel)
        {
//            if([nsFM fileExistsAtPath:xmlPath])
//                [nsFM removeItemAtPath:xmlPath error:nil];
//            
//            [self initializeCancel:PresentFolder];
            break;
        }
        
		NSString *img = ResourceOB.RID;
		NSString *imagePath;
        
        
        if(![ResourceOB.Type isEqualToString:@"MOV"])    
            imagePath = [NSString stringWithFormat:@"%@/%@",PresentFolder, img];
        else
            imagePath = [NSString stringWithFormat:@"%@/%@.mov",PresentFolder, img];
        
        if([nsFM fileExistsAtPath:imagePath isDirectory:&isDir])
        {
            int fileSize = [[nsFM attributesOfItemAtPath:imagePath error:nil]fileSize];
            
            NSLog(@"ActualSize=%d, SpecSize=%d", fileSize, ResourceOB.fileSize);
            
            if(fileSize == ResourceOB.fileSize){
                download = FALSE;
            } else {
                download = TRUE;
            }
        }
        else if(!download)
            download = YES;
        
		
		if(download)
		{
			//NSLog(@"Downloading %@", img);
            
            if(![ResourceOB.Type isEqualToString:@"MOV"])
            {
                NSData *imageData = [imageRequest Image_PostRequest:authenticationXML urlString:[NSString stringWithFormat:@"%@/%d/%@", m_ResourcePath , PresentID, img]];
                
                // NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(respondImg)];
                
                if(imageRequest.httpError != nil)
                    NSLog(@"Code: %d\tDomain: %@\tDescription: %@", [imageRequest.httpError code], [imageRequest.httpError domain], [imageRequest.httpError localizedDescription]);
                
                if(imageData != NULL)
                {
                    @try {
                        [imageData writeToFile:imagePath atomically:YES];
                    }
                    @catch (NSException* ex) {
                        NSLog(@"imageData Initialized Fail: %@",ex);
                        imageCorrupted = TRUE;
                    }
                }
                
                if([imageData length] < 1)
                    imageCorrupted = TRUE;
                
                //[imageData release];
            }
            else
            {
                NSData *respondVideo = [imageRequest Video_PostRequest:authenticationXML urlString:[NSString stringWithFormat:@"%@/%d/%@", m_ResourcePath , PresentID, img]];
                
                if(respondVideo != NULL)
                {
                    @try {
                        [respondVideo writeToFile:imagePath atomically:NO];
                    }
                    @catch(NSException* ex) {
                        NSLog(@"imageData Initialized Fail: %@",ex);
                        imageCorrupted = TRUE;
                    }
                }
            }
        }
		
		
        		
		//[imageRequest release];
		//imageData.release; Autorelease was applied.
		
		
        [resourcePool release];
        
        progress = i/(float)[mu_Arr_Resources count];
        [self updateProgress];
        i++;
	}
    
    if([mu_Arr_Resources count] < 1){
        progress = 1;
        [self updateProgress];
    }
    
    //
}

-(void)updateProgress{
    NSString *pString = [NSString stringWithFormat:@"%f", progress];
    [self performSelectorOnMainThread:@selector(UpdateProgressBar:) withObject:pString waitUntilDone:NO];
}

-(void)initializeCancel:(NSString *)PresentFolder
{
    [self DeleteLoopFiles:PresentFolder];
    [_delegate BarUpdate:0];
}

-(void)DeleteLoopFiles:(NSString *)dirName
{
	NSFileManager *nsFM = [NSFileManager defaultManager];
	
	NSArray *delOB = [nsFM contentsOfDirectoryAtPath:dirName error:nil];
	
	for (NSString *file in delOB)
		[nsFM removeItemAtPath:[NSString stringWithFormat:@"%@/%@",dirName, file] error:nil];
}


#pragma mark -
#pragma mark Update HomeView Component

-(void)UpdateWaitingLabel:(NSString *)Gan
{
    [_delegate DisplayWaiting:[Gan boolValue]];
}

-(void)UpdateWaitingWithBlocked{
    [_delegate DisplayBlocked];
}


-(void)UpdateProgressBar:(NSString *)updateProgress
{
	[_delegate BarUpdate:[updateProgress floatValue]];
}

-(AD_Slide*)SetHomeEndPage:(AD_Image*) imageOB
                   SlideID:(int)SlideID
{    
    AD_Slide *SlideOB = [[AD_Slide alloc] autorelease];
    SlideOB.SlideID =SlideID;
    SlideOB.mut_Arr_Pages = [NSMutableArray array];
    SlideOB.PageIdLookup = [NSMutableDictionary dictionary];
    AD_Page *PageOB = [[AD_Page alloc] init];
    PageOB.pageID = 1;
    PageOB.parentSlide = SlideOB;
    PageOB.pageType = @"CurrentSlide";
    PageOB.transition = @"Cut";
    
    [PageOB.mut_Arr_Images addObject:imageOB];    
    [SlideOB.mut_Arr_Pages addObject:PageOB];
    [PageOB release];
    
    return SlideOB;
}

#pragma mark -
#pragma mark Load XML 

-(void)LoadXML:(NSData *)xmlData
	PresentDir:(NSString *)PresentationDirectory
{
	NSError *nerr = nil;
	
    
	GDataXMLDocument *docXML = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&nerr];
	
	//GDataXMLElement *ConfNode = [[docXML  nodesForXPath:@"//init" error:nil] objectAtIndex:0];
    
	NSDictionary *namespaces = [NSDictionary dictionaryWithObjectsAndKeys:
								@"http://www.activedeck.com/PowerPoint/", @"ad",
								nil];
	
	GDataXMLElement *PresentNode = [[docXML nodesForXPath:@"//ad:Presentation" namespaces:namespaces error:&nerr] objectAtIndex:0];
    
    if([PresentNode elementsForName:@"WebService"]){
        GDataXMLElement *WebServiceElement = [[PresentNode elementsForName:@"WebService"] objectAtIndex:0];
        webServiceEndPoint = [[NSString alloc] initWithString:[[WebServiceElement attributeForName:@"Endpoint"] stringValue]];
        hasSecondarySubscription = YES;
        channelFormat = [[NSString alloc] initWithString:[[WebServiceElement attributeForName:@"ChannelFormat"] stringValue]];
    } else {
        webServiceEndPoint = @"";
        hasSecondarySubscription = NO;
        channelFormat = @"";
    }
    
	iVersion = [[[PresentNode attributeForName:@"Version"]stringValue]intValue];
	xmlnsLink = [[PresentNode attributeForName:@"xmlns"] stringValue];
	
	mu_Arr_Resources = [[NSMutableArray alloc]init];
	mu_Arr_Slides = [[NSMutableArray alloc]init];
    
    
    NSArray *ar_KioskConfig = [docXML nodesForXPath:@"//ad:Presentation/ad:KioskConfiguration" namespaces:namespaces error:&nerr];
    for (GDataXMLElement *Kiosk in ar_KioskConfig)
    {
        Conf_Kiosk = [AD_Kiosk alloc];
        Conf_Kiosk.enabled = [[[Kiosk attributeForName:@"Enabled"]stringValue]boolValue];
        
        /******test Code ************/
        //Conf_Kiosk.enabled = FALSE;
        
        /******test code *************/
        NSString *to = [[Kiosk attributeForName:@"Timeout"]stringValue];
        NSDateFormatter *timeFormatter = [[NSDateFormatter alloc]init];
        [timeFormatter setDateFormat:@"HH:mm:ss"];
        
        NSDate *date = [timeFormatter dateFromString:to];
        
        [timeFormatter setDateFormat:@"HH"];
        int hr = [[timeFormatter stringFromDate:date]intValue];
        [timeFormatter setDateFormat:@"mm"];
        int min = [[timeFormatter stringFromDate:date]intValue];
        [timeFormatter setDateFormat:@"ss"];
        int sec = [[timeFormatter stringFromDate:date]intValue];
        
        Conf_Kiosk.Timeout = hr * 60 * 60 + min * 60 + sec;
        
        Conf_Kiosk.AutoUpdate = [[[Kiosk attributeForName:@"AutoUpdate"]stringValue]boolValue];
        
        NSArray *attModes = [Kiosk elementsForName:@"AttractMode"];
        for (GDataXMLElement *attMode in attModes)
        {
            Conf_Kiosk.attractPage = [[[attMode attributeForName:@"Page"]stringValue]intValue];
            Conf_Kiosk.attractSlide = [[[attMode attributeForName:@"Section"]stringValue]intValue];
        }
        
        NSArray *userModes = [Kiosk elementsForName:@"UserMode"];
        for (GDataXMLElement *userMode in userModes)
        {
            Conf_Kiosk.userPage = [[[userMode attributeForName:@"Page"]stringValue]intValue];
            Conf_Kiosk.userSlide = [[[userMode attributeForName:@"Section"]stringValue]intValue];
        }
        
        GDataXMLElement *idleMessage = [[Kiosk elementsForName:@"IdleMessage"] objectAtIndex:0];
        
        if(idleMessage){
            Conf_Kiosk.idleMessage = [[idleMessage attributeForName:@"Message"] stringValue];
            Conf_Kiosk.channelFormat = [[idleMessage attributeForName:@"ChannelFormat"] stringValue];
        }
        
        NSLog(@"Timeout in Second : %d", Conf_Kiosk.Timeout);
        NSLog(@"attractPage:%d, userPage:%d", Conf_Kiosk.attractPage, Conf_Kiosk.userPage);
        [timeFormatter release];
    }    
    
    if ([[[docXML rootElement] elementsForName:@"ExportToPDF"] count] > 0) {
        canExportToPDF = [[[[[[docXML rootElement] elementsForName:@"ExportToPDF"] objectAtIndex:0] attributeForName:@"Allow"] stringValue] boolValue];
    } else {
        canExportToPDF = YES;
    }
    
    
	NSArray *ar_Resources = [docXML nodesForXPath:@"//ad:Presentation/ad:Resources/ad:Resource" namespaces:namespaces error:&nerr];
	for(GDataXMLElement *resource in ar_Resources)
	{
		AD_Resource *ResourceOB = [AD_Resource alloc];
		
		ResourceOB.RID = [[resource attributeForName:@"ID"]stringValue];
        ResourceOB.Type = [[resource attributeForName:@"Type"]stringValue];
		ResourceOB.fileSize = [[[resource attributeForName:@"Size"]stringValue] intValue];
		
		[mu_Arr_Resources addObject:ResourceOB];
		[ResourceOB release];
	}
    
    NSArray *homePageArray = [docXML nodesForXPath:@"//ad:Presentation/ad:HomePage" namespaces:namespaces error:&nerr];
    
    if ([homePageArray count] > 0) {
        GDataXMLElement *HomePageNode = [homePageArray objectAtIndex:0];
        AD_Image *imageOB = [AD_Image alloc];
        imageOB.top = 0;
        imageOB.left = 0;
        imageOB.width = 768;
        imageOB.height = 1024;
        imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[HomePageNode attributeForName:@"ResourceID"] stringValue]];
        AD_Slide *homeSlide = [self SetHomeEndPage:imageOB
                                           SlideID:0];
        [mu_Arr_Slides addObject:homeSlide];
        [imageOB release];
        [homeSlide release];
    }
    
    
    NSArray *EndPageArray = [docXML nodesForXPath:@"//ad:Presentation/ad:EndPage" namespaces:namespaces error:&nerr];
    
    if ([EndPageArray count] > 0) {
        GDataXMLElement *EndPageNode = [EndPageArray objectAtIndex:0];
        
        AD_Image *imageOB = [AD_Image alloc];
        imageOB.top = 0;
        imageOB.left = 0;
        imageOB.width = 768;
        imageOB.height = 1024;
        imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[EndPageNode attributeForName:@"ResourceID"] stringValue]];
        AD_Slide *EndSlide = [self SetHomeEndPage:imageOB
                                          SlideID:-1];
        [mu_Arr_Slides addObject:EndSlide];
        [imageOB release];
        [EndSlide release];
    }
    
   	
	NSArray *ar_SlideConfigs = [docXML nodesForXPath:@"//ad:Presentation/ad:SlideConfig" namespaces:namespaces error:&nerr];
	for (GDataXMLElement *slideConfig in ar_SlideConfigs) {
		AD_Slide *SlideOB = [AD_Slide alloc];
		
		SlideOB.SlideID = [[[slideConfig attributeForName:@"SlideID"]stringValue]intValue];
		SlideOB.mut_Arr_Pages = [NSMutableArray array];
		SlideOB.PageIdLookup = [NSMutableDictionary dictionary];
        SlideOB.Submit = FALSE;
        
		NSArray *pages = [slideConfig elementsForName:@"Page"];
		for(GDataXMLElement *page in pages)
		{
			AD_Page *PageOB = [[AD_Page alloc] init];
			PageOB.pageID = [[[page attributeForName:@"ID"]stringValue]intValue];
			PageOB.parentSlide = SlideOB;
            
			//Get the Background Image
			//TODO: Is there a better way to do this if we know there is only one element?
			NSArray *backgroundImages = [page elementsForName:@"BackgroundImage"];
			for(GDataXMLElement *img in backgroundImages)
			{
				PageOB.imageBG = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[img attributeForName:@"ResourceID"]stringValue]];
			}
			
			//PageOB.imageBG = [[page attributeForName:@"BackgroundImage"]stringValue];
			PageOB.pageType = [[page attributeForName:@"Type"]stringValue]; 
            
            if([page attributeForName:@"NavigateForward"]){
                PageOB.canNavigateForwards = [[[page attributeForName:@"NavigateForward"] stringValue] boolValue];
            } else {
                PageOB.canNavigateForwards = YES;
            }
            
            if ([page attributeForName:@"NavigateBackward"]) {
                PageOB.canNavigateBackwards = [[[page attributeForName:@"NavigateBackward"] stringValue] boolValue];
            } else {
                PageOB.canNavigateBackwards = YES;
            }
            
            if ([page attributeForName:@"Orientation"]) {
                NSArray *orientations = [[[page attributeForName:@"Orientation"] stringValue] componentsSeparatedByString:@"|"]; 
                
                for(NSString *o in orientations){
                    if ([o isEqualToString:@"Portrait"]) {
                        [PageOB.mut_Arr_Orientations addObject:[NSNumber numberWithInt:UIDeviceOrientationPortrait]];
                    } else if ([o isEqualToString:@"LandscapeLeft"]){
                        [PageOB.mut_Arr_Orientations addObject:[NSNumber numberWithInt:UIDeviceOrientationLandscapeLeft]];                        
                    } else if ([o isEqualToString:@"LandscapeRight"]){
                        [PageOB.mut_Arr_Orientations addObject:[NSNumber numberWithInt:UIDeviceOrientationLandscapeRight]];
                    } else if ([o isEqualToString:@"UpsideDown"]){
                        [PageOB.mut_Arr_Orientations addObject:[NSNumber numberWithInt:UIDeviceOrientationPortraitUpsideDown]];
                    }
                }
            } else {
                PageOB.mut_Arr_Orientations = nil;
            }
            
            if ([page attributeForName:@"StatusBar"]) {
                PageOB.showStatusBar = ([[[page attributeForName:@"StatusBar"] stringValue] isEqualToString:@"true"] ? YES : NO);
            } else {
                PageOB.showStatusBar = YES;
            }
            
            GDataXMLElement *gradingNode = [[page elementsForName:@"Grading"] objectAtIndex:0];
            if(gradingNode != nil){
                AD_Grade *grade = [[AD_Grade alloc] init];
                grade.hasInstantFeedback = [[[gradingNode attributeForName:@"InstantFeedback"]stringValue]boolValue];
                grade.correctAnswerFeedback = [[gradingNode attributeForName:@"CorrectAnswerFeedback"]stringValue];
                grade.incorrectAnswerFeedback = [[gradingNode attributeForName:@"IncorrectAnswerFeedback"]stringValue];
                
                AD_Question *question = [[AD_Question alloc] init];
                question.questionText = [[[[gradingNode elementsForName:@"Question"] objectAtIndex:0] attributeForName:@"Text"] stringValue];
                
                if ([PageOB.pageType isEqualToString:@"MultipleChoiceQuestion"] || [PageOB.pageType isEqualToString:@"ShortAnswerQuestion"]) {
                    
                    if ([PageOB.pageType isEqualToString:@"MultipleChoiceQuestion"]) {
                        for (GDataXMLElement *mcAnswer in [gradingNode elementsForName:@"Answer"]){
                            [grade.PossibleMultipleChoiceAnswers setObject:[[mcAnswer attributeForName:@"Text"] stringValue] forKey:[[mcAnswer attributeForName:@"ID"] stringValue]];
                        }
                    }
                    
                    NSArray *correctAnswers = [gradingNode elementsForName:@"CorrectAnswer"]; 
                    for (GDataXMLElement *a in correctAnswers) {
                        if ([PageOB.pageType isEqualToString:@"MultipleChoiceQuestion"]) {
                            NSString *value = [[a attributeForName:@"Value"]stringValue];
                            
                            [grade.CorrectAnswers addObject: value];  
                            
                            
                            
                            [question.correctAnswerText appendString:[grade.PossibleMultipleChoiceAnswers objectForKey:value]];
                        } else if ([PageOB.pageType isEqualToString:@"ShortAnswerQuestion"]){
                            [grade.CorrectAnswers addObject: [[a attributeForName:@"Text"]stringValue]];
                            [question.correctAnswerText appendString:[[a attributeForName:@"Text"]stringValue]];
                        }                        
                    }  
                } else if ([PageOB.pageType isEqualToString:@"Categories"]) {
                    NSArray *categories = [gradingNode elementsForName:@"Category"];
                    GDataXMLElement *words = [[page elementsForName:@"Words"] objectAtIndex:0];
                    NSArray *correctWordCategories = [gradingNode elementsForName:@"Word"];
                    NSMutableString *correctCategoryAnswerText = [[NSMutableString alloc] init];
                    
                    
                    for (GDataXMLElement *w in correctWordCategories) {
                        [grade.CorrectWordCategories setObject:[[w attributeForName:@"CorrectCategory"] stringValue] forKey:[[w attributeForName:@"ID"] stringValue]];                         
                    }
                    
                    if([categories count] > 0){
                        [correctCategoryAnswerText appendString:@"\n"];
                    }
                    for (GDataXMLElement *c in categories) {
                        [correctCategoryAnswerText appendFormat:@"%@(", [[c attributeForName:@"Text"] stringValue]];                        
                        [question.possibleCategories setObject:[[c attributeForName:@"Text"] stringValue] forKey:[[c attributeForName:@"ID"] stringValue]];
                        
                        for(GDataXMLElement *cwc in correctWordCategories){
                            if ([[[cwc attributeForName:@"CorrectCategory"] stringValue] isEqualToString:[[c attributeForName:@"ID"] stringValue]]) {
                                for (GDataXMLElement *w in [words elementsForName:@"Word"]){
                                    [question.possibleWords setObject:[[w attributeForName:@"Text"] stringValue] forKey:[[w attributeForName:@"ID"] stringValue]];
                                    if([[[w attributeForName:@"ID"] stringValue] isEqualToString:[[cwc attributeForName:@"ID"] stringValue]]){
                                        [correctCategoryAnswerText appendString:[[w attributeForName:@"Text"] stringValue]];
                                        [correctCategoryAnswerText appendString:@", "];
                                    }
                                }
                            }
                        }      
                        if([correctCategoryAnswerText hasSuffix:@", "]){
                            
                            NSRange endRange = NSMakeRange([correctCategoryAnswerText length]-2, 2);
                            [correctCategoryAnswerText replaceCharactersInRange:endRange withString:@""];
                            
                        }
                        [correctCategoryAnswerText appendString:@")\n"];
                    }    
                    
                    if([correctCategoryAnswerText hasSuffix:@"\n"]){
                        
                        NSRange endRange = NSMakeRange([correctCategoryAnswerText length]-1, 1);
                        [correctCategoryAnswerText replaceCharactersInRange:endRange withString:@""];
                        
                    }
                    
                    
                    question.correctAnswerText = correctCategoryAnswerText;
                }                
                
                grade.question = question;
                [question release];
                
                PageOB.grade = grade;
                [grade release];
            }
            
            if([PageOB.pageType isEqualToString:@"ScoreReport"]){
                NSArray *ScoreReportQuestions = [[[page elementsForName:@"ReportList"] objectAtIndex:0] elementsForName:@"Question"];
                for(GDataXMLElement *q in ScoreReportQuestions){                    
                    [PageOB.mut_Arr_ScoreReportQuestions addObject:[NSString stringWithString:[[q attributeForName:@"Page"] stringValue]]];
                }
            }
            
            
            //Get and set the transition property
            PageOB.transition = [[page attributeForName:@"Transition"]stringValue];
            
            PageOB.oneTime = [[[page attributeForName:@"OneTime"]stringValue]boolValue];
            
            if([page attributeForName:@"TrackNavigation"]){
                PageOB.trackNavigation = [[[page attributeForName:@"TrackNavigation"]stringValue]boolValue];
            } else {
                PageOB.trackNavigation = YES;
            }
            
			NSArray *buttons = [page elementsForName:@"Button"];
			for(GDataXMLElement *button in buttons)
			{
				AD_Button* ButtonOB = [self CreateButton:button PresentDir:PresentationDirectory];
				
				[PageOB.mut_Arr_Button addObject:ButtonOB];
				[ButtonOB release];
			}
			
			NSArray *TextBoxes = [page elementsForName:@"TextBox"];
			for(GDataXMLElement *textBox in TextBoxes)
			{
				AD_TextBox *textBoxOB = [AD_TextBox alloc];
				textBoxOB.Name = [[textBox attributeForName:@"Name"]stringValue];
				textBoxOB.top = [[[textBox attributeForName:@"Top"]stringValue]intValue];
				textBoxOB.left = [[[textBox attributeForName:@"Left"]stringValue]intValue];
				textBoxOB.width = [[[textBox attributeForName:@"Width"]stringValue]intValue];
				textBoxOB.height = [[[textBox attributeForName:@"Height"]stringValue]intValue];
				textBoxOB.fontSize = 24;  //Default
				GDataXMLNode * fontSizeNode = [textBox attributeForName:@"FontSize"];
				if(fontSizeNode){
					textBoxOB.fontSize = [[fontSizeNode stringValue]intValue];
				}
				[PageOB.mut_Arr_TextBox addObject:textBoxOB];
				[textBoxOB release];
			}
			
			NSArray *Categories = [page elementsForName:@"Category"];
			for(GDataXMLElement *category in Categories)
			{
				AD_Category *categoryOB = [AD_Category alloc];
				categoryOB.Value = [[[category attributeForName:@"Value"]stringValue]intValue];
				categoryOB.Top = [[[category attributeForName:@"Top"]stringValue]intValue];
				categoryOB.Left = [[[category attributeForName:@"Left"]stringValue]intValue];
				categoryOB.Width = [[[category attributeForName:@"Width"]stringValue]intValue];
				categoryOB.Height = [[[category attributeForName:@"Height"]stringValue]intValue];
				categoryOB.beTop = [[[[[category elementsForName:@"BucketEdge"]objectAtIndex:0]attributeForName:@"Top"]stringValue]intValue];
				categoryOB.beLeft = [[[[[category elementsForName:@"BucketEdge"]objectAtIndex:0]attributeForName:@"Left"]stringValue]intValue];
				categoryOB.beWidth = [[[[[category elementsForName:@"BucketEdge"]objectAtIndex:0]attributeForName:@"Width"]stringValue]intValue];
				categoryOB.beHeight = [[[[[category elementsForName:@"BucketEdge"]objectAtIndex:0]attributeForName:@"Height"]stringValue]intValue];
				
				categoryOB.bcWidth = [[[[[category elementsForName:@"BucketCap"]objectAtIndex:0]attributeForName:@"Width"]stringValue]intValue];
				categoryOB.bcHeight = [[[[[category elementsForName:@"BucketCap"]objectAtIndex:0]attributeForName:@"Height"]stringValue]intValue];
                
				categoryOB.bucketCap = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[[[[[category elementsForName:@"BucketCap"]objectAtIndex:0]elementsForName:@"Image"]objectAtIndex:0]attributeForName:@"ResourceID"]stringValue]];
				categoryOB.bucketEdge = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[[[[[category elementsForName:@"BucketEdge"]objectAtIndex:0]elementsForName:@"Image"]objectAtIndex:0]attributeForName:@"ResourceID"]stringValue]];
				categoryOB.bucket = [[NSMutableArray	alloc]init];
				
				[PageOB.mut_Arr_Category addObject:categoryOB];
				[categoryOB release];
			}
			
			NSArray *WordsGroup = [page elementsForName:@"Words"];
			for(GDataXMLElement *words in WordsGroup)
			{
				AD_Words *wordsOB = [[AD_Words alloc]initArray];
				wordsOB.color = [[words attributeForName:@"Color"]stringValue];
				wordsOB.count = [[[words attributeForName:@"Count"]stringValue]intValue];
				
				
				NSArray *wds = [words elementsForName:@"Word"];
				for (GDataXMLElement *wd in wds)
				{
					AD_Word *wordTextOB = [AD_Word alloc];
					wordTextOB.wordID = [[[wd attributeForName:@"ID"]stringValue]intValue];
					wordTextOB.text = [[wd attributeForName:@"Text"]stringValue];
					
					[wordsOB.mut_Arr_Words addObject:wordTextOB];
					[wordTextOB release];
				}
				
				NSArray *spOBs = [words elementsForName:@"StartPosition"];
				for (GDataXMLElement *sp in spOBs) {
					
					CGPoint StartPosition = CGPointMake([[[sp attributeForName:@"Left"]stringValue]intValue], [[[sp attributeForName:@"Top"]stringValue]intValue]);
					
					[wordsOB.mut_Arr_StartPoistion addObject:[NSValue valueWithCGPoint:StartPosition]];
				}
				
				[PageOB.mut_Arr_Words addObject:wordsOB];
				[wordsOB release];
			}
			
			NSArray *Images = [page elementsForName:@"Image"];
			for(GDataXMLElement *img in Images)
			{
				AD_Image *imageOB = [AD_Image alloc];
                imageOB.ZoomEnabled = [[[img attributeForName:@"ZoomEnabled"]stringValue]boolValue];
                imageOB.top = [[[img attributeForName:@"Top"]stringValue]intValue];
                imageOB.left = [[[img attributeForName:@"Left"]stringValue]intValue];
                imageOB.width = [[[img attributeForName:@"Width"]stringValue]intValue] > 0 ? [[[img attributeForName:@"Width"]stringValue]intValue] : 768;
                imageOB.height = [[[img attributeForName:@"Height"]stringValue]intValue] > 0 ? [[[img attributeForName:@"Height"]stringValue]intValue] :1024;
				imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[img attributeForName:@"ResourceID"]stringValue]];
                imageOB.Condition = [[img attributeForName:@"Condition"]stringValue];
				[PageOB.mut_Arr_Images addObject:imageOB];
				[imageOB release];
			}
			
			NSArray *Graphic = [page elementsForName:@"Graphic"];
			for(GDataXMLElement *img in Graphic)
			{
				AD_Image *imageOB = [AD_Image alloc];
				imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[img attributeForName:@"ID"]stringValue]];
				PageOB.imageOB = imageOB;
				[imageOB release];
			}
            
            NSArray *Videos = [page elementsForName:@"Video"];
            for (GDataXMLElement *vid in Videos)
            {
                AD_Video *videoOB = [AD_Video alloc];
                videoOB.top = [[[vid attributeForName:@"Top"]stringValue]intValue];
                videoOB.left = [[[vid attributeForName:@"Left"]stringValue]intValue];
                videoOB.width = [[[vid attributeForName:@"Width"]stringValue]intValue];
                videoOB.height = [[[vid attributeForName:@"Height"]stringValue]intValue];
                videoOB.orientation = [[vid attributeForName:@"Orientation"]stringValue];
                
                NSArray *medias = [vid elementsForName:@"Media"];
                for(GDataXMLElement *media in medias)
                    videoOB.mediaName = [NSString stringWithFormat:@"%@/%@.mov", PresentationDirectory, [[media attributeForName:@"ResourceID"]stringValue]];
                
                NSLog(@"VideoPath%@", videoOB.mediaName);
                
                [PageOB.mut_Arr_Videos addObject:videoOB];
                [videoOB release];
            }
            
            NSArray *ViewPorts = [page elementsForName:@"Viewport"];
			for (GDataXMLElement *vp in ViewPorts)
            {
                AD_ViewPort *vpOB = [[AD_ViewPort alloc]init];
                vpOB.top = [[[vp attributeForName:@"Top"]stringValue]intValue];
                vpOB.left = [[[vp attributeForName:@"Left"]stringValue]intValue];
                vpOB.Width = [[[vp attributeForName:@"Width"]stringValue]intValue];
                vpOB.Height = [[[vp attributeForName:@"Height"]stringValue]intValue];
                vpOB.ZoomEnabled = [[[vp attributeForName:@"ZoomEnabled"]stringValue]boolValue];
                vpOB.VerticalOffset = [[[vp attributeForName:@"VerticalOffset"]stringValue]intValue];
                vpOB.HorizontalOffSet = [[[vp attributeForName:@"HorizontalOffset"]stringValue]intValue];
                
                GDataXMLElement *vpImageBG = [[vp elementsForName:@"BackgroundImage"]objectAtIndex:0];
                vpOB.ImageBG = [NSString stringWithFormat:@"%@/%@", PresentationDirectory, [[vpImageBG attributeForName:@"ResourceID"]stringValue]];
                NSArray *vpbuttons = [vp elementsForName:@"Button"];
                for(GDataXMLElement *button in vpbuttons)
                {
                    AD_Button* vButtonOB = [self CreateButton:button PresentDir:PresentationDirectory];
                    
                    [vpOB.AD_ButtonSets addObject:vButtonOB];
                    [vButtonOB release];
                }
                
                NSArray *vpImages = [vp elementsForName:@"Image"];
                for(GDataXMLElement *image in vpImages){
                    AD_Image* imageOB = [AD_Image alloc];
                    imageOB.top = [[[image attributeForName:@"Top"]stringValue]intValue];
                    imageOB.left = [[[image attributeForName:@"Left"]stringValue]intValue];
                    imageOB.width = [[[image attributeForName:@"Width"]stringValue]intValue] > 0 ? [[[image attributeForName:@"Width"]stringValue]intValue] : 768;
                    imageOB.height = [[[image attributeForName:@"Height"]stringValue]intValue] > 0 ? [[[image attributeForName:@"Height"]stringValue]intValue] :1024;
                    imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[image attributeForName:@"ResourceID"]stringValue]];
                    imageOB.Movement = 100 - [[[image attributeForName:@"Movement"]stringValue]intValue];
                    imageOB.Condition = [[image attributeForName:@"Condition"]stringValue];
                    [vpOB.AD_ImageSets addObject:imageOB];
                    [imageOB release];
                }
                
                NSArray *webViews = [vp elementsForName:@"WebView"];
                for(GDataXMLElement *webView in webViews){
                    AD_WebView *webViewOB = [AD_WebView alloc];
                    
                    webViewOB.urlAddress = [[webView attributeForName:@"Url"] stringValue];
                    webViewOB.width = [[[webView attributeForName:@"Width"] stringValue] intValue];
                    webViewOB.height = [[[webView attributeForName:@"Height"] stringValue] intValue];
                    webViewOB.left = [[[webView attributeForName:@"Left"] stringValue] intValue];
                    webViewOB.top = [[[webView attributeForName:@"Top"] stringValue] intValue];
                    webViewOB.showScrollBars = [[[webView attributeForName:@"ShowScrollBars"] stringValue] boolValue];
                    
                    [vpOB.AD_WebViewSets addObject:webViewOB];
                    [webViewOB release];
                }
                
                [PageOB.mut_Arr_ViewPorts addObject:vpOB];
                [vpOB release];
            }
            
            NSArray *ParallaxSlide = [page elementsForName:@"ParallaxSlide"];
			for (GDataXMLElement *ps in ParallaxSlide)
            {
                AD_ParallaxView *psOB = [[AD_ParallaxView alloc]init];
                psOB.top = [[[ps attributeForName:@"Top"]stringValue]intValue];
                psOB.left = [[[ps attributeForName:@"Left"]stringValue]intValue];
                psOB.Width = [[[ps attributeForName:@"Width"]stringValue]intValue];
                psOB.Height = [[[ps attributeForName:@"Height"]stringValue]intValue];
                
                GDataXMLElement *psImageBG = [[ps elementsForName:@"BackgroundImage"]objectAtIndex:0];
                psOB.ImageBG = [NSString stringWithFormat:@"%@/%@", PresentationDirectory, [[psImageBG attributeForName:@"ResourceID"]stringValue]];
                
                NSArray *psImages = [ps elementsForName:@"Image"];
                for(GDataXMLElement *image in psImages)
                {
                    AD_Image *imageOB = [AD_Image alloc];
                    imageOB.top = [[[image attributeForName:@"Top"]stringValue]intValue];
                    imageOB.left = [[[image attributeForName:@"Left"]stringValue]intValue];
                    imageOB.width = [[[image attributeForName:@"Width"]stringValue]intValue] > 0 ? [[[image attributeForName:@"Width"]stringValue]intValue] : 768;
                    imageOB.height = [[[image attributeForName:@"Height"]stringValue]intValue] > 0 ? [[[image attributeForName:@"Height"]stringValue]intValue] :1024;
                    imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[image attributeForName:@"ResourceID"]stringValue]];
                    imageOB.Movement = 100 - [[[image attributeForName:@"Movement"]stringValue]intValue];
                    [psOB.AD_ImageSet addObject:imageOB];
                    [imageOB release];
                }
                
                NSArray *psbuttons = [ps elementsForName:@"Button"];
                for(GDataXMLElement *button in psbuttons)
                {
                    AD_Button* pButtonOB = [self CreateButton:button PresentDir:PresentationDirectory];
                    pButtonOB.Movement = 100 - [[[button attributeForName:@"Movement"]stringValue]intValue];
                    [psOB.AD_ButtonSets addObject:pButtonOB];
                    [pButtonOB release];
                }
                [PageOB.mut_Arr_ParallaxView addObject:psOB];
                [psOB release];
            }
            
            
            NSArray *Layers = [page elementsForName:@"Layer"];
            for (GDataXMLElement *layer in Layers)
            {
                AD_Layer *layOB = [[AD_Layer alloc]init];
                layOB.top = [[[layer attributeForName:@"Top"]stringValue]intValue];
                layOB.left = [[[layer attributeForName:@"Left"]stringValue]intValue];
                layOB.Width = [[[layer attributeForName:@"Width"]stringValue]intValue];
                layOB.Height = [[[layer attributeForName:@"Height"]stringValue]intValue];
                
                layOB.ID = MaxViewTag - [[[layer attributeForName:@"ID"]stringValue]intValue];
                layOB.Name = [[layer attributeForName:@"Name"]stringValue];
                layOB.Enabled = [[[layer attributeForName:@"Enabled"]stringValue]boolValue];
                layOB.AutoHide = [[[layer attributeForName:@"AutoHide"]stringValue]boolValue];
                layOB.Condition = [[layer attributeForName:@"Condition"]stringValue];
                
                NSArray *Images = [layer elementsForName:@"Image"];
                for(GDataXMLElement *img in Images)
                {
                    AD_Image *imageOB = [AD_Image alloc];
                    imageOB.top = [[[img attributeForName:@"Top"]stringValue]intValue];
                    imageOB.left = [[[img attributeForName:@"Left"]stringValue]intValue];
                    imageOB.width = [[[img attributeForName:@"Width"]stringValue]intValue] > 0 ? [[[img attributeForName:@"Width"]stringValue]intValue] : 768;
                    imageOB.height = [[[img attributeForName:@"Height"]stringValue]intValue] > 0 ? [[[img attributeForName:@"Height"]stringValue]intValue] :1024;
                    imageOB.imagePath = [NSString stringWithFormat:@"%@/%@", PresentationDirectory,[[img attributeForName:@"ResourceID"]stringValue]];
                    imageOB.Condition = [[img attributeForName:@"Condition"]stringValue];
                    [layOB.AD_ImageSets addObject:imageOB];
                    [imageOB release];
                }
                
                NSArray *layButtons = [layer elementsForName:@"Button"];
                for (GDataXMLElement *button in layButtons)
                {
                    AD_Button* lButtonOB = [self CreateButton:button PresentDir:PresentationDirectory];
                    
                    [layOB.AD_ButtonSets addObject:lButtonOB];
                    [lButtonOB release];
                }
                
                NSArray *Videos = [layer elementsForName:@"Video"];
                for (GDataXMLElement *vid in Videos)
                {
                    AD_Video *videoOB = [AD_Video alloc];
                    videoOB.top = [[[vid attributeForName:@"Top"]stringValue]intValue];
                    videoOB.left = [[[vid attributeForName:@"Left"]stringValue]intValue];
                    videoOB.width = [[[vid attributeForName:@"Width"]stringValue]intValue];
                    videoOB.height = [[[vid attributeForName:@"Height"]stringValue]intValue];
                    videoOB.orientation = [[vid attributeForName:@"Orientation"]stringValue];
                    
                    NSArray *medias = [vid elementsForName:@"Media"];
                    for(GDataXMLElement *media in medias)
                        videoOB.mediaName = [NSString stringWithFormat:@"%@/%@.mov", PresentationDirectory, [[media attributeForName:@"ResourceID"]stringValue]];
                    
                    NSLog(@"VideoPath%@", videoOB.mediaName);
                    
                    [layOB.AD_VideoSets addObject:videoOB];
                    [videoOB release];
                }
                
                [PageOB.mut_Arr_Layers addObject:layOB];
                [layOB release];
            }
            
            
            
			
			[SlideOB.PageIdLookup setObject:[NSNumber numberWithInt:[SlideOB.mut_Arr_Pages count]]
                                     forKey:[NSNumber numberWithInt:PageOB.pageID]];
            [SlideOB.mut_Arr_Pages addObject:PageOB];
            [PageOB release];
			
			//AutoRelease Applied
			//buttons.release;
			//TextBoxs.release;
			//Categories.release;
			//Words.release;
			//Images.release;
		}
		[mu_Arr_Slides addObject:SlideOB];
		[SlideOB release];
	}
    
    [docXML release];
}

-(AD_Button*)CreateButton:(GDataXMLElement *)button
               PresentDir:(NSString*)PresentationDirectory
{
    AD_Button *ButtonOB = [AD_Button alloc];
    ButtonOB.actions = [[NSMutableArray alloc] initWithCapacity:[[button elementsForName:@"Action"] count]]; 
    ButtonOB.top = [[[button attributeForName:@"Top"]stringValue] intValue];
    ButtonOB.left = [[[button attributeForName:@"Left"]stringValue] intValue];
    ButtonOB.width = [[[button attributeForName:@"Width"]stringValue]intValue];
    ButtonOB.height = [[[button attributeForName:@"Height"]stringValue]intValue];
    ButtonOB.Condition = [[button attributeForName:@"Condition"]stringValue];
    
    //ButtonOB.actions = [[NSMutableArray alloc] init];
    
    for(GDataXMLElement *action in [button elementsForName:@"Action"]){
        NSString* type = [NSString stringWithString:[[action attributeForName:@"Type"] stringValue]];
        
        if([type isEqualToString:@"GoTo"]){
            Action_GoTo* gt = [[Action_GoTo alloc] init];
            
            gt.section = [[[action attributeForName:@"Section"] stringValue] intValue];
            gt.page = [[[action attributeForName:@"Page"] stringValue] intValue];
            
            if([action attributeForName:@"HOffset"]){
                gt.hOffset = [[[action attributeForName:@"HOffset"] stringValue] intValue];
            } else {
                gt.hOffset = 0;
            }
            
            if ([action attributeForName:@"VOffset"]) {
                gt.vOffset = [[[action attributeForName:@"VOffset"] stringValue] intValue];
            } else {
                gt.vOffset = 0;
            }
            
            [ButtonOB.actions addObject:gt];
            
            // [gt release];
        } else if ([type isEqualToString:@"Command"]){
            Action_Command* command = [[Action_Command alloc] init];
            
            command.method = [[action attributeForName:@"Method"] stringValue];
            command.data = [[[action elementsForName:@"Data"] objectAtIndex:0] stringValue];   
            command.endpoint = webServiceEndPoint;
            command.PID = PID;
            
            [ButtonOB.actions addObject:command];
            
            //[command release];
        } else if ([type isEqualToString:@"Layer"]){
            Action_Layer* layer = [[Action_Layer alloc] init];
            
            layer.TargetID = MaxViewTag - [[[action attributeForName:@"Target"] stringValue] intValue];
            layer.state = [[action attributeForName:@"State"]stringValue]; 
            
            [ButtonOB.actions addObject:layer];
            
            //[layer release];
        } else if ([type isEqualToString:@"Next"]){
            Action_Next* next = [[Action_Next alloc] init];
            
            [ButtonOB.actions addObject:next];
            //[next release];
        } else if ([type isEqualToString:@"Reset"]){
            Action_Reset* reset = [[Action_Reset alloc] init];
            
            [ButtonOB.actions addObject:reset];
            //[reset release];
        } else if ([type isEqualToString:@"Save"]){
            Action_Save* save = [[Action_Save alloc] init];
            
            [ButtonOB.actions addObject:save];    
            //[save release];
        } else if ([type isEqualToString:@"Submit"]){
            Action_Submit* submit = [[Action_Submit alloc] init];
            
            [ButtonOB.actions addObject:submit];   
            //[submit release];
        } else if ([type isEqualToString:@"Toggle"]){
            Action_Toggle* toggle = [[Action_Toggle alloc] init];
            
            toggle.Value = [[[action attributeForName:@"Value"]stringValue] intValue];
            
            [ButtonOB.actions addObject:toggle];
            //[toggle release];
        } else if ([type isEqualToString:@"Back"]){
            Action_Back* back = [[Action_Back alloc] init];
            
            [ButtonOB.actions addObject:back];
            //[back release];
        }
    }
    
    //    ButtonOB.buttonType = [[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"Type"]stringValue];
    //    ButtonOB.value = [[[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"Value"]stringValue]intValue];
    //    ButtonOB.section = [[[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"Section"]stringValue]intValue];
    //    ButtonOB.TargetID =  MaxViewTag - [[[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"Target"]stringValue]intValue];
    //    ButtonOB.State = [[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"State"]stringValue];
    
    
    
    
    
    //    ButtonOB.page = [[[[[button elementsForName:@"Action"]objectAtIndex:0]attributeForName:@"Page"]stringValue]intValue];
    NSString *resId = [[[[button elementsForName:@"ImageOn"]objectAtIndex:0]attributeForName:@"ResourceID"]stringValue];
    ButtonOB.imageOn = [[NSString alloc] initWithFormat:@"%@/%@", PresentationDirectory,resId];
    resId = [[[[button elementsForName:@"ImageOff"]objectAtIndex:0]attributeForName:@"ResourceID"]stringValue];
    ButtonOB.imageOff = [[NSString alloc] initWithFormat:@"%@/%@", PresentationDirectory,resId];
    
    return ButtonOB;
    
}

-(BOOL)CheckVersion
{
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	NSString *presentKeyID = [NSString stringWithFormat:@"activeDeck_%d", PID];
	int version = [prefs integerForKey:presentKeyID];
	
	if(version != iVersion)
	{
		[prefs setObject:[NSNumber numberWithInt:iVersion] forKey:presentKeyID];
		return TRUE;
	}
	else 
		return FALSE;
}

-(void)CheckResume
{
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	Resume = [prefs boolForKey:@"activeDeckSessionLive"];
}

- (void)dealloc {
    [xmlnsLink release];
    [mu_Arr_Resources release];
    [mu_Arr_Slides release];
    [Conf_Kiosk release];
    [super dealloc];
}


@end
